// Package bootstrap config 配置文件加载
package bootstrap

import (
	"bookkeeping-gin/global"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"os"
	"path/filepath"
	"strings"
)

func InitConfig() {
	// 获取当前工作目录的路径
	wd, err := os.Getwd()
	if err != nil {
		panic(fmt.Errorf("get working directory failed: %s \n", err))
	}
	fmt.Println("working directory:", wd)
	// config path
	// 获取配置文件的完整路径
	configFile := filepath.Join(strings.Replace(wd, "test", "", 1), "config/config.yaml")
	// 从env获取配置文件
	if configEnv := os.Getenv("VIPER_CONFIG"); configEnv != "" {
		configFile = configEnv
	}
	// viper
	v := viper.New()
	v.SetConfigFile(configFile)
	v.SetConfigType("yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(fmt.Errorf("read config failed: %s \n", err))
	}

	// listen
	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed:", e.Name)

		// reload
		if err := v.Unmarshal(&global.App.Config); err != nil {
			panic(fmt.Errorf("unmarshal config failed: %s \n", err))
		}
	})

	// init
	if err := v.Unmarshal(&global.App.Config); err != nil {
		panic(fmt.Errorf("unmarshal config failed: %s \n", err))
	}
}
